package servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ecs.xml.XML;

import server.DBLogic;
import server.resources.XMLFactory;

import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJaxbRestClient;

import facebook.FacebookUserFilter;
import facebook.FacebookUtils;
import game.resources.Profile;


public class GetUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DBLogic dbl = new DBLogic();
        dbl.InitDBConnection();
        
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        
        String requestType = request.getParameter("type");
        
        XML resp = new XML("status");
        
        FacebookJaxbRestClient client = FacebookUserFilter.getUserClientJaxb(request.getSession());
        
        try {
            Profile user = FacebookUtils.getFacebookProfile(client);
            if (requestType.equals("getUserDetails")) {
                if (user == null) {
                    resp.addElement("no-user");
                } else {
                    
                    Cookie cookie = new Cookie("userID" , Long.toString(user.getUserID()));
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    
                    String profileXML = XMLFactory.getProfileXML(user);
                    resp.addElement(profileXML);
                }
            } else if (requestType.equals("postOnWall")) {
                FacebookUtils.postChallangeOnWall(client, user);
                resp.addElement("post");
            } else if (requestType.equals("updateWinnerStatus")) {
                FacebookUtils.updateWinnerStatus(client, user);
                resp.addElement("post");
            } else {
                resp.addElement("bad-command");
            }
        } catch (SQLException e) {
            response.getWriter().write("<status>");
            e.printStackTrace(response.getWriter());
            dbl.ShutDBConnection();
            response.getWriter().write("</status>");
            return;
        } catch (FacebookException e) {
            response.getWriter().write("<you>");
            e.printStackTrace(response.getWriter());
            response.getWriter().write("</you>");
            dbl.ShutDBConnection();
            return;
        }

        response.getWriter().write(resp.toString());
        dbl.ShutDBConnection();
    }

}
